﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TYAJZWeb.Models;
using TYAJZWeb.Data;
using TYAJZWeb.Utils;
using System.Text;
using System.Web.Routing;
using OfficeOpenXml;


namespace TYAJZWeb.Controllers
{
    public class EquipmentController : BaseController
    {
        [CookiesAuthorize]
        public ActionResult List(int page, EquipmentSearchModel model)
        {
            IQueryable<Equipment> r = Context.Equipments.Where(t => t.IsDeleted == false);
            if (!String.IsNullOrEmpty(Request.QueryString["Name"]))
            {
                int name = 0;
                if (int.TryParse(Request.QueryString["Name"], out name))
                    r = r.Where(t => t.Eq_Name == name);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["NO"]))
                r = r.Where(t => t.Eq_no.Contains(Request.QueryString["NO"]));

            if (model != null)
            {
                if (!String.IsNullOrEmpty(model.CertNO))
                    r = r.Where(t => t.Eq_CertNo.Contains(model.CertNO));

                DateTime tempDT = DateTime.Now;

                if (!String.IsNullOrEmpty(model.CreateDT_Start))
                {
                    if (DateTime.TryParse(model.CreateDT_Start, out tempDT))
                    {
                        r = r.Where(t => t.CreateDT > tempDT);
                    }
                }

                if (!String.IsNullOrEmpty(model.CreateDT_End))
                {
                    if (DateTime.TryParse(model.CreateDT_End, out tempDT))
                    {
                        r = r.Where(t => t.CreateDT < tempDT);
                    }
                }

                if (!String.IsNullOrEmpty(model.RegisterDT_End))
                {
                    if (DateTime.TryParse(model.RegisterDT_End, out tempDT))
                    {
                        r = r.Where(t => t.CertDate > tempDT);
                    }
                }

                if (!String.IsNullOrEmpty(model.RegisterDT_Start))
                {
                    if (DateTime.TryParse(model.RegisterDT_Start, out tempDT))
                    {
                        r = r.Where(t => t.CertDate < tempDT);
                    }
                }

                //if (!String.IsNullOrEmpty(model.NO_Start))
                //{
                //    r = r.Where(t => t.Eq_no > model.NO_Start);
                //}

                //if (!String.IsNullOrEmpty(model.NO_End))
                //{
                //    r = r.Where(t => t.Eq_no < model.NO_End);
                //}

                if (!String.IsNullOrEmpty(model.OwnerName))
                {
                    r = r.Where(t => t.Eq_Owner.Contains(model.OwnerName) || t.Company.Name.Contains(model.OwnerName));
                }

                if (!String.IsNullOrEmpty(model.Name))
                {
                    r = r.Where(t => t.Eq_Name == Convert.ToInt32(model.Name));
                }

                if (!String.IsNullOrEmpty(model.EquipmentModel))
                    r = r.Where(t => t.Eq_Type.Contains(model.EquipmentModel));

                if (!String.IsNullOrEmpty(model.ProductCompany))
                    r = r.Where(t => t.Company1.Name.Contains(model.ProductCompany));

                if (!String.IsNullOrEmpty(model.MadeNo))
                    r = r.Where(t => t.Eq_MadeNo.Contains(model.MadeNo));

                int limitMonth = 0;
                if (!String.IsNullOrEmpty(model.LimitedYear_Start) && int.TryParse(model.LimitedYear_Start, out limitMonth))
                    r = r.Where(t => t.LimitedMonth >= limitMonth * 12);


                if (!String.IsNullOrEmpty(model.LimitedYear_End) && int.TryParse(model.LimitedYear_End, out limitMonth))
                    r = r.Where(t => t.LimitedMonth <= limitMonth * 12);

                if (model.IsWorking && !model.IsAvailable)
                    r = r.Where(t => t.Eq_Status == (EquipmentStatus.Working.ToString()));

                if (model.IsAvailable && !model.IsWorking)
                    r = r.Where(t => t.Eq_Status != (EquipmentStatus.Working.ToString()));

                if (model.IsExpired)
                    r = r.Where(t => t.Eq_MadeDate.AddMonths(t.LimitedMonth) < DateTime.Now);

                if (!string.IsNullOrEmpty(model.NO_Start))
                    r = r.Where(t => string.Compare(t.Eq_no, model.NO_Start) > -1);

                if (!string.IsNullOrEmpty(model.NO_End))
                    r = r.Where(t => string.Compare(t.Eq_no, model.NO_End) < 1);

            }

            if (!String.IsNullOrEmpty(Request.QueryString["Local"]))
            {
                var local = Request.QueryString["Local"].ToUpper();
                if (local == "TRUE")
                    r = r.Where(t => t.IsLocal == true);
                else
                    r = r.Where(t => t.IsLocal == false);
            }

            if (!String.IsNullOrEmpty(Request.QueryString["Destory"]))
            {
                var local = Request.QueryString["Destory"].ToUpper();
                if (local == "TRUE")
                    r = r.Where(t => t.Eq_Status == EquipmentStatus.Destoryed.ToString());
                else
                    r = r.Where(t => t.Eq_Status != EquipmentStatus.Destoryed.ToString());
            }
            else
            {
                r = r.Where(t => t.Eq_Status != EquipmentStatus.Destoryed.ToString());
            }

            if (!String.IsNullOrEmpty(model.NO_End) || !String.IsNullOrEmpty(model.NO_Start))
                r = r.OrderBy(t => t.Eq_no);
            else
                r = r.OrderByDescending(t => t.Id);

            var r1 = r.Select(t => (EquipmentListModel)t);
            int totalCount = r.Count();
            r1 = r1.Skip((page - 1) * PAGESIZE).Take(PAGESIZE);
            return View(new PageList<EquipmentListModel>(r1, page, PAGESIZE, totalCount));
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult AddLocal()
        {
            ViewBag.Names = Context.EquipmentTypes.Select(t =>
                new SelectListItem()
                {
                    Value = t.Id.ToString(),
                    Text = t.Name
                }).ToList();
            return View("EditLocal");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult AddLocal(EquipmentEditLocalModel model)
        {
            if (ModelState.IsValid)
            {
                Equipment c = (Equipment)model;
                c.CertDate = DateTime.Now;
                c.CreateDT = DateTime.Now;
                c.ModifiedDT = DateTime.Now;
                c.LastmodifiedUser = CurrentUserId;
                c.IsDeleted = false;
                c.Eq_no = c.Eq_no ?? string.Empty;
                c.Eq_Comment = c.Eq_Comment ?? string.Empty;
                c.Eq_InspectNO = string.Empty;
                Context.Equipments.InsertOnSubmit(c);

                Context.SubmitChanges();

                var maxNo = Context.Equipments.Where(t => t.IsLocal == true && t.Eq_Name == model.Eq_Name).OrderByDescending(t => t.Eq_no).Take(1).ToList()[0].Eq_no.Substring(4);
                c.Eq_no = String.Format("{0}{1:D5}", c.EquipmentType.Prefix, int.Parse(maxNo) + 1);

                Context.SubmitChanges();

                Log log = new Log()
                {
                    CreateDT = DateTime.Now,
                    LastModifiedUser = CurrentUserId,
                    Type = LogTypes.Equipment.ToString(),
                    Value = String.Format("新增记录, {0}", c.Id),
                    RefId = c.Id,
                    OperatorType = OperatorType.Create.ToString()
                };
                Context.Logs.InsertOnSubmit(log);

                Context.SubmitChanges();

                TempData.Add("Success", "新设备备案成功");

                return RedirectToAction("Detail", new { Id = c.Id });
            }

            ViewBag.OwnerCompanies = Context.Companies.Where(t => t.IsDeleted == false && t.CanLend == true).Select(t =>
                new SelectListItem()
                {
                    Value = t.Id.ToString(),
                    Text = t.Name
                }).ToList();

            ViewBag.ProductCompanies = Context.Companies.Where(t => t.IsDeleted == false && t.CanProduct == true).Select(t =>
                new SelectListItem()
                {
                    Value = t.Id.ToString(),
                    Text = t.Name
                }).ToList();

            ViewBag.Names = Context.EquipmentTypes.Select(t =>
                new SelectListItem()
                {
                    Value = t.Id.ToString(),
                    Text = t.Name
                }).ToList();
            return View("EditLocal", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult AddExternal()
        {
            ViewBag.Names = Context.EquipmentTypes.Select(t =>
               new SelectListItem()
               {
                   Value = t.Id.ToString(),
                   Text = t.Name
               }).ToList();
            return View("EditExternal");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult AddExternal(EquipmentEditExternalModel model)
        {
            if (ModelState.IsValid)
            {
                if (Context.Equipments.Count(t => t.Eq_no == model.Eq_NO) == 0)
                {

                    Equipment c = (Equipment)model;
                    c.CertDate = DateTime.Now;
                    c.CreateDT = DateTime.Now;
                    c.ModifiedDT = DateTime.Now;
                    c.LastmodifiedUser = Convert.ToInt32(HttpContext.Items["UserId"]);
                    c.IsDeleted = false;
                    c.Eq_InspectNO = string.Empty;

                    Context.Equipments.InsertOnSubmit(c);
                    Context.SubmitChanges();

                    Log log = new Log()
                    {
                        CreateDT = DateTime.Now,
                        LastModifiedUser = CurrentUserId,
                        Type = LogTypes.Equipment.ToString(),
                        Value = String.Format("新增记录, {0}", c.Id),
                        RefId = c.Id,
                        OperatorType = OperatorType.Create.ToString()
                    };
                    Context.Logs.InsertOnSubmit(log);

                    Context.SubmitChanges();

                    TempData.Add("Success", "新设备信息登记成功");

                    return RedirectToAction("Detail", new { Id = c.Id });
                }
                else
                {
                    TempData.Add("Error", "该起重设备备案编号已存在");
                }
            }
            ViewBag.Names = Context.EquipmentTypes.Select(t =>
               new SelectListItem()
               {
                   Value = t.Id.ToString(),
                   Text = t.Name
               }).ToList();
            return View("EditExternal", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Edit(int id)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            if (equipment != null)
            {
                return View("EditAll", (EquipmentEditModel)equipment);
            }
            return View("Error");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Edit(EquipmentEditModel model)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == model.Id);
            if (equipment != null)
            {

                equipment.Eq_no = model.Eq_No ?? string.Empty;
                equipment.Eq_InspectNO = model.InspectNO ?? string.Empty;
                equipment.LimitedMonth = model.LimitedYears * 12;
                Context.SubmitChanges();
                return RedirectToAction("Detail", new { Id = model.Id });
            }
            return View("EditALL", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult EditLocal(int id)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            if (equipment != null)
            {
                ViewBag.Names = Context.EquipmentTypes.Select(t =>
                    new SelectListItem()
                    {
                        Value = t.Id.ToString(),
                        Text = t.Name
                    }).ToList();

                return View("EditLocal", (EquipmentEditLocalModel)equipment);
            }
            return View("Error");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult EditLocal(EquipmentEditLocalModel model)
        {
            return RedirectToAction("List");
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult EditExternal(int id)
        {
            return View();
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult EditExternal(EquipmentEditExternalModel model)
        {
            return RedirectToAction("List");
        }

        [CookiesAuthorize]
        public ActionResult Delete(int id)
        {
            var c = Context.Equipments.Single(t => t.Id == id);
            EquipmentStatus status = EquipmentStatus.Available;
            Enum.TryParse<EquipmentStatus>(c.Eq_Status, out status);
            if (status == EquipmentStatus.Available)
            {
                c.IsDeleted = true;
                Context.SubmitChanges();

                Log log = new Log()
                {
                    CreateDT = DateTime.Now,
                    LastModifiedUser = CurrentUserId,
                    Type = LogTypes.Equipment.ToString(),
                    Value = String.Format("删除记录, {0}", c.Id),
                    RefId = c.Id,
                    OperatorType = OperatorType.Delete.ToString()
                };
                Context.Logs.InsertOnSubmit(log);

                Context.SubmitChanges();
                TempData.Add("Success", "删除成功");
            }
            else if (status == EquipmentStatus.Working)
            {
                TempData.Add("Error", "该设备在工作状态，不能删除");
            }

            return RedirectToAction("List");

        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Destory(int id)
        {
            var c = Context.Equipments.Single(t => t.Id == id);
            EquipmentStatus status = EquipmentStatus.Available;
            Enum.TryParse<EquipmentStatus>(c.Eq_Status, out status);
            if (status == EquipmentStatus.Available)
            {
                c.Eq_Status = EquipmentStatus.Destoryed.ToString();
                Context.SubmitChanges();

                Log log = new Log()
                {
                    CreateDT = DateTime.Now,
                    LastModifiedUser = CurrentUserId,
                    Type = LogTypes.Equipment.ToString(),
                    Value = String.Format("报废记录, {0}", c.Id),
                    RefId = c.Id,
                    OperatorType = OperatorType.Destory.ToString()
                };
                Context.Logs.InsertOnSubmit(log);

                Context.SubmitChanges();
                TempData.Add("Success", "报废成功");
            }
            else if (status == EquipmentStatus.Working)
            {
                TempData.Add("Error", "该设备在工作状态，不能报废");
            }

            return RedirectToAction("List");

        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Search()
        {
            ViewBag.Names = Context.EquipmentTypes.Select(t =>
                new SelectListItem()
                {
                    Value = t.Id.ToString(),
                    Text = t.Name
                }).ToList();

            return View();
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Search(EquipmentSearchModel model)
        {
            //StringBuilder sb = new StringBuilder();
            //if (!String.IsNullOrEmpty(model.NO))
            //    sb.AppendFormat("&NO={0}", model.NO);
            //if (!String.IsNullOrEmpty(model.Name))
            //    sb.AppendFormat("&Name={0}", model.Name);
            RouteValueDictionary dic = new RouteValueDictionary(model);

            return RedirectToAction("List", dic);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Detail(int id)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            if (equipment != null)
            {
                if (equipment.IsLocal)
                {
                    return View("DetailLocal", (EquipmentDetailLocalModel)equipment);
                }
                else
                {
                    return View("DetailExternal", (EquipmentDetailExternalModel)equipment);
                }
            }
            return View("Error");
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Print(int id)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            if (equipment != null)
            {
                if (equipment.IsLocal)
                {
                    return View("PrintLocal", (EquipmentPrintLocalModel)equipment);
                }
                else
                {
                    return View("PrintExternal", (EquipmentPrintExternalModel)equipment);
                }
            }
            return View("Error");
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Archive(int id = 0)
        {
            if (id == 0)
            {
                return RedirectToAction("ArchiveSearch");
            }
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            if (equipment != null)
            {
                return View((EquipmentArchiveModel)equipment);
            }
            return View("Error");
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult ArchiveSearch()
        {
            return View();
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult ArchiveSearch(string no)
        {
            if (!String.IsNullOrEmpty(no))
            {
                var equipment = Context.Equipments.SingleOrDefault(t => t.Eq_no == no);
                if (equipment != null)
                    return RedirectToAction("Archive", new { id = equipment.Id });
                else
                {
                    TempData.Add("Error", "未找到该设备");
                    return View();
                }
            }
            TempData.Add("Error", "设备备案号不能为空");
            return View(no);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Archive(EquipmentArchiveModel model)
        {
            if (ModelState.IsValid)
            {
                var equipment = Context.Equipments.SingleOrDefault(t => t.Id == model.Id);
                equipment.Eq_RecDeskNo = model.Eq_RecDeskNo;
                equipment.Eq_RecBoxNo = model.Eq_RecBoxNo;
                Context.SubmitChanges();
                TempData.Add("Success", "设备归档成功");
                return RedirectToAction("Detail", new { Id = equipment.Id });
            }
            return View(model);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult PrintSuccess(int id)
        {
            var equipment = Context.Equipments.SingleOrDefault(t => t.Id == id);
            equipment.Eq_IsPrinted = true;
            Context.SubmitChanges();
            return new ContentResult() { Content = "true" };
        }

        [CookiesAuthorize]
        [HttpGet]
        public JsonResult Suggestion(String term)
        {
            var list = Context.Equipments.Where(t => t.Eq_no.Contains(term) && t.IsDeleted == false)
                .Select(t => new SuggestionModel()
                {
                    label = t.Eq_no,
                    Value = t.Eq_no
                }).Take(100).ToList();

            return new JsonResult() { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult EditContactor(int id)
        {
            var e = Context.Equipments.SingleOrDefault(t => t.Id == id);
            return View((EquipmentContactorModel)e);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult EditContactor(EquipmentContactorModel m)
        {
            var e = Context.Equipments.SingleOrDefault(t => t.Id == m.Id);
            e.Eq_Phone = m.Phone;
            e.Eq_InCharge = m.Legal;
            Context.SubmitChanges();
            return RedirectToAction("Detail", new { Id = m.Id });
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult ExportToExcel()
        {
            var fileName = Server.MapPath(String.Format("~/Upload/过期设备{0}止.xlsx", DateTime.Now.ToString("yyyy-MM-dd")));
            if (!System.IO.File.Exists(fileName))
            {
                using (ExcelPackage excelHandler = new ExcelPackage(new System.IO.FileInfo(fileName)))
                {
                    var sheet = excelHandler.Workbook.Worksheets.Add("过期设备");
                    var equipments = Context.Equipments.Where(t => t.IsDeleted == false && t.Eq_Status != EquipmentStatus.Destoryed.ToString()
                        && t.Eq_MadeDate.AddMonths(t.LimitedMonth) < DateTime.Now).Select(t => (EquipmentListModel)t).ToList();
                    sheet.InsertRow(0, equipments.Count + 1);
                    sheet.SetValue("A1", "备案编号");
                    sheet.SetValue("B1", "报检号");
                    sheet.SetValue("C1", "产权单位");
                    sheet.SetValue("D1", "设备名称");
                    sheet.SetValue("E1", "设备型号");
                    sheet.SetValue("F1", "合格证号");
                    sheet.SetValue("G1", "出厂日期");
                    sheet.SetValue("H1", "出厂代号");
                    sheet.SetValue("I1", "状态");
                    sheet.SetValue("J1", "设计年限");
                    sheet.SetValue("K1", "已用年限");
                    for (int i = 0; i < equipments.Count; i++)
                    {
                        sheet.SetValue(String.Format("A{0}", i + 2), equipments[i].NO);
                        sheet.SetValue(String.Format("B{0}", i + 2), equipments[i].InspectNO);
                        sheet.SetValue(String.Format("C{0}", i + 2), equipments[i].Eq_Owner);
                        sheet.SetValue(String.Format("D{0}", i + 2), equipments[i].Eq_Name);
                        sheet.SetValue(String.Format("E{0}", i + 2), equipments[i].Eq_Type);
                        sheet.SetValue(String.Format("F{0}", i + 2), equipments[i].Eq_CertNo);
                        sheet.SetValue(String.Format("G{0}", i + 2), equipments[i].Eq_MadeDate.ToString("yyyy-MM-dd"));
                        sheet.SetValue(String.Format("H{0}", i + 2), equipments[i].Eq_MadeNo);
                        sheet.SetValue(String.Format("I{0}", i + 2), equipments[i].StatusString);
                        sheet.SetValue(String.Format("J{0}", i + 2), equipments[i].Eq_LimitMonths);
                        sheet.SetValue(String.Format("K{0}", i + 2), equipments[i].Eq_HaveUsedMonths);
                    }
                    excelHandler.Save();
                }

            }

            return new FileContentResult(System.IO.File.ReadAllBytes(fileName), "application/vnd.ms-excel") { FileDownloadName = fileName.Substring(fileName.LastIndexOf('\\') + 1) };

        }
    }
}
